var app = getApp()
//常量数据配置
var ConstantData = require('../../../common/constant_data.js')
var common = require("../../../common/common.js")
var util = require('../../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showMaintPlatform: false,
    showUseOtherMini: false,
    platformTipDesc: '',
    noLoginFlg: false,
    miniImg: {
      icHos: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-hos.png',
    },
    beeBannerHeight: 0,
    beeBannerConfig: null,
    pageNum: 1,
    numPerPage: 10,
    // leseList:[],
    payStatus: true,
    callServiceBoxStatus: false,
    pt: '',
    showDialog: false,
    show: true //取消预约后 按钮展示
  },

  clickBeeBanner() {
    wx.navigateToMiniProgram({
      appId: this.data.beeBannerConfig.appId,
      path: this.data.beeBannerConfig.path,
      success(res) {
        console.log('【小蜜蜂广告跳转】跳转成功：' + JSON.stringify(res))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30003, '租金明细-小蜜蜂底部广告', 'success')
      },
      fail(error) {
        console.log('【小蜜蜂广告跳转】跳转失败：' + JSON.stringify(error))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30003, '租金明细-小蜜蜂底部广告', 'fail')
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.bee_record_page_uv('用户租金明细列表', '/pages/user_record/lease/user_lease')
    if (app.globalData.miniBeeConfig && app.globalData.miniBeeConfig.lease_list) {
      if (app.globalData.miniBeeConfig.lease_list.active == 1) {
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30003, '租金明细-小蜜蜂底部广告', 'read')
      }
      this.setData({
        beeBannerConfig: app.globalData.miniBeeConfig.lease_list
      })
    }

    this.getNetwork()
    if (options.pt == 'backsuc') {
      //从归还成功后跳转过来的
      this.setData({
        pt: 'backsuc',
        refundEqTid: options.refundeqtid,
        refundTip: options.refundtip,
        isRefundTip: options.isRefundTip
      });
    }
    this.getApageLeaseRecord()
  },
  cancel() {
    var that = this
    app.executeRequest(function (header) {
      wx.request({
        url: app.BASE_URL + '/reserve_lease/cancelReserve',
        method: 'post',
        header: header,
        success: (res) => {
          console.log(res, 'resresres')
          that.setData({
            showDialog: false,
            pageNum: 1,
            leseList: [],
          });
          that.getApageLeaseRecord()
        }
      })
    })
  },
  navIndex() {
    console.log("跳转到扫码页面")
    wx.reLaunch({
      url: '../../index/index?autoPlay=true',
    })
  },
  openConfirm: function () {
    this.setData({
      showDialog: true
    });
  },
  closeConfirm: function () {
    this.setData({
      showDialog: false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.globalData.userStay = false

    wx.createSelectorQuery().in(this).select('.bottom-banner').boundingClientRect().exec((res) => {
      if (res && res[0]) {
        this.setData({
          beeBannerHeight: res[0].height
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (this.data.alertBoxStatus) {
      this.setData({
        alertBoxStatus: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    if (that.data.loading && !that.data.loadingComplete) {
      that.setData({
        pageNum: 1, //每次触发上拉事件，把searchPageNum+1  
        dropDown:1
      });
      that.getApageLeaseRecord();
    }
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    console.log(33333)
    if (that.data.loading && !that.data.loadingComplete) {
      that.setData({
        pageNum: that.data.pageNum + 1, //每次触发上拉事件，把searchPageNum+1  
      });
      that.getApageLeaseRecord();
    }
  },
  // onscrolbottom:function(){
  //   var that = this;
  //   if (that.data.loading && !that.data.loadingComplete) {
  //     that.setData({
  //       pageNum: that.data.pageNum + 1, //每次触发上拉事件，把searchPageNum+1  
  //     });
  //     that.getApageLeaseRecord();
  //   }
  // },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '进入小程序，点击“扫码还”按钮扫描桩上二维码进行归还',
      path: '/pages/index/index',
      imageUrl: '../../../image/picture.jpg',
      success: () => {
        wx.showToast({
          title: '分享成功',
        })
      }
    }
  },
  /**
   * 监听网络状态
   */
  getNetwork: function () {
    var that = this;
    wx.getNetworkType({
      success: function (res) {
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        let networkType = res.networkType
        that.setData({
          networkType: networkType
        })
      }
    })
    if (wx.onNetworkStatusChange) {
      wx.onNetworkStatusChange(function (res) {
        console.log(res)
        let networkType = res.networkType
        let isConnected = res.isConnected
        that.setData({
          networkType: networkType,
          isConnected: isConnected
        })
        if (isConnected) {
          if (that.data.leseList.length > 0) {
            if (that.data.loading && !that.data.loadingComplete) {
              that.setData({
                pageNum: that.data.pageNum + 1,
              });
            } else {
              return
            }
          } else {
            that.setData({
              pageNum: 1,
            });
          }
          that.getApageLeaseRecord();
        }
      })
    }

  },
  getApageLeaseRecord: function () {
    if (app.globalData.loginData && app.globalData.loginData.nophone == 1) {
      //需要重新登录      
      this.setData({
        noLoginFlg: true
      })
      return
    }
    if (this.data.refundTip == 1) {

      wx.redirectTo({
        url: '../deposit/user_deposit?refundtip=1',
      })

    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var that = this
    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/wxmini/record_list',
        method: 'post',
        header: header,
        data: {
          numPerPage: that.data.numPerPage,
          pageNum: that.data.pageNum
        },
        success: function (res) {
          console.log("userRecordsList-->", res);
          that.setData({
            networkType: ''
          })
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.result == 0) {
            //归还成功后弹框提示是否去退押金
            if (that.data.isRefundTip && that.data.isRefundTip == 1 && that.data.pageNum == 1 && res.data.ispaydeposit && res.data.ispaydeposit > 0 && that.data.pt == 'backsuc') {
              that.setData({
                callServiceBoxStatus: true,
                callServiceTipContent: "是否去申请退押金?"
              })
            }
            if(that.data.dropDown){
              that.data.leseList=[]
            }
            var oldList = that.data.leseList || []
            var newList = oldList.concat(res.data.data.data)
            newList.forEach(item => {
              if (typeof item.consumePrice == 'number') {
                item.consumePrice = item.consumePrice.toString().split('.')
              }
            })
            var tobePaidList = newList.filter(item => {
              return item.stat == 1 && (item.payStat == 1 || item.payStat == 0) && item.orderType != 1000
            })
            var reservationList = newList.filter(item => {
              return item.orderType == 1000
            })
            var inUseList = newList.filter(item => {
              return item.stat == 0 && item.orderType != 1000
            })
            var returnedList = newList.filter(item => {
              return item.stat == 1 && item.payStat == 2 && item.orderType != 1000
            })
            console.log(785285858, tobePaidList, inUseList, returnedList)
            if (res.data.data.pageNum * that.data.numPerPage >= res.data.data.total) {
              that.setData({
                loading: false,
                loadingComplete: true,
                leseList: newList,
                tobePaidList: tobePaidList,
                reservationList: reservationList,
                inUseList: inUseList,
                returnedList: returnedList
              });
            } else {
              that.setData({
                loading: true,
                loadingComplete: false,
                leseList: newList,
                tobePaidList: tobePaidList,
                reservationList: reservationList,
                inUseList: inUseList,
                returnedList: returnedList
              });
            }
          } else {
            wx.showToast({
              title: '获取失败'
            })
          }
        },
        complete() {
          that.setData({
            dropDown:0
          })
          getApp().hideLoading()
        }
      })

    })

  },
  toNoDepositDetail: function (event) {
    var extdata = event.currentTarget.dataset.extdata;
    console.log("------>>extdata=", extdata);
    if (extdata) {
      wx.navigateToMiniProgram({
        appId: 'wxd8f3793ea3b935b8',
        path: "pages/record/detail",
        extraData: extdata
      })
    }
  },
  toNoBackTip: function (e) {
    let equId = e.currentTarget.dataset.equId
    let hospitalName = e.currentTarget.dataset.hospitalName
    let positions = e.currentTarget.dataset.positions
    let equType = e.currentTarget.dataset.type
    let orderCode = e.currentTarget.dataset.ordercode
    wx.navigateTo({
      url: '/pages/index/no_back_tip/no_back_tip?equId=' + equId + "&hospitalName=" + hospitalName + '&positions=' + positions + '&pt=user_lease' + '&equType=' + equType + "&orderCode=" + orderCode,
    })
  },
  toPayLease: function (event) {
    var orderCode = event.currentTarget.dataset.ordercode
    this.toPay(orderCode)
  },
  toPay: function (orderCode) {
    var that = this
    if (that.data.payStatus) {} else {
      console.log("支付中。。。。")
      return
    }
    that.setData({
      payStatus: false
    })
    console.log("去支付。。。" + orderCode)

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/unpay/payment',
        method: 'post',
        header: header,
        data: {
          ordernum: orderCode
        },
        success: function (res) {
          var data = res.data
          console.log("支付结果---" + data.result)
          if (data.result == 0) {
            that.setData({
              alertBoxStatus: true,
              msg: data.description,
              pageNum: 1,
              leseList: []
            })
            that.getApageLeaseRecord()
            console.log("刷新支付记录")
          } else if (data.result == -1) {
            console.log("开始微信支付")
            that.toPayOrder(orderCode)
          } else {
            that.setData({
              alertBoxStatus: true,
              msg: data.description
            })
          }

        },
        complete: function (res) {
          console.log("恢复支付")
          that.setData({
            payStatus: true
          })
        }
      })

    })

  },
  toPayOrder: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              console.log("租金支付失败----result=" + data.result + ",description=" + data.description)
              that.setData({
                msg: data.description ? data.description : "支付失败",
                alertBoxStatus: true
              })
              return
            }
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res);

                that.setData({
                  pageNum: 1, //每次触发上拉事件，把searchPageNum+1  
                  leseList: []
                });
                that.getApageLeaseRecord();
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'ulea-' + JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          },
          complete: function (res) {
            console.log("恢复支付。。。")
            that.setData({
              payStatus: true
            })
          }
        })

      })

    });


  },
  sureTip: function () {
    this.setData({
      alertBoxStatus: false
    })
  },
  toHome: function () {
    wx.redirectTo({
      url: '../../index/index',
    })
  },
  sureBtnClick: function () {
    if (this.data.refundEqTid) {
      //直接退款再跳转到租金列表
      this.toRefundDeposit(this.data.refundEqTid);
    } else {
      wx.redirectTo({
        url: '../deposit/deposit',
      })
    }
  },
  cancelBtnClick: function () {
    this.setData({
      callServiceBoxStatus: false,
      callServiceTipContent: ""
    });
  },

  /**
   * 去退押金
   */
  toRefundDeposit: function (eqTid) {

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/refund_d',
        method: 'post',
        header: header,
        data: {
          eqTid: eqTid
        },
        success: function (res) {
          var tip = 0;
          if (res.data.result == 0) {
            tip = 1;
          }
          wx.redirectTo({
            url: '../deposit/user_deposit?refundtip=' + tip,
          })
        },
        fail: function (res) {
          wx.redirectTo({
            url: '../deposit/user_deposit',
          })
        }
      })

    })

  },
  ontoRefundDeposit:function(){
    wx.redirectTo({
      url: '../deposit/user_deposit',
    })
  },
  /**
   * 返回首页
   */
  backHome: function () {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  //详情页面
  toDetail: function (e) {
    let data = e.currentTarget.dataset.data
    data = JSON.stringify({
      ...data
    })
    wx.navigateTo({
      url: '/pkgNew/pages/orderDetails/index?data=' + encodeURIComponent(data),
    })
  }

})